package com.guandi.geekbrowser.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guandi.geekbrowser.Utils.DESHelper;
import com.guandi.geekbrowser.Utils.EasyUtil;
import com.guandi.geekbrowser.primary.entity.Ipool;
import com.guandi.geekbrowser.primary.entity.Message;
import com.guandi.geekbrowser.primary.service.IpoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class ServiceController {

    @Autowired
    private IpoolService ipoolService;

    private DESHelper desHelper = new DESHelper("zDsGrVKQ");

    @RequestMapping(value = "/getCCPIp", method = RequestMethod.POST)
    @ResponseBody
    public List<Ipool> getCCPIp(@RequestBody JSONObject jsonObject) {
        //2019年5月8日10:02:13 使用luminati 废弃ccp
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        if (!EasyUtil.isEmpty(userId)&&!EasyUtil.isEmpty(country)) {
            userId = desHelper.decrypt(userId);
            List<Ipool> ccpIps = ipoolService.findByUserIdUseStatusTypeCountryBindOrderByPortASC(userId,0, 0, 0,country);
            List<Ipool> ccpList = new ArrayList<>();
            ccpIps.stream().forEach(f -> {
                ccpList.add(f);
            });
            return ccpList;
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/updateIpManage", method = RequestMethod.POST)
    @ResponseBody
    public String updateIpManage(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        Object updateIpForm = jsonObject.get("updateIpForm");
        String s = JSONObject.toJSONString(updateIpForm);
        JSONObject tempObj = JSONObject.parseObject(s);
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(country)) {
            userId = desHelper.decrypt(userId);
            String id = tempObj.getString("id");
            String address = tempObj.getString("address");
            String proxyUser = tempObj.getString("proxyUser");
            String port = tempObj.getString("port");
            String proxyPassword = tempObj.getString("proxyPassword");
            Integer type = 0; //use luminati old =>tempObj.getInteger("type");
            if (!EasyUtil.isEmpty(address) && !EasyUtil.isEmpty(port)) {
                if (!EasyUtil.isEmpty(proxyUser) && !EasyUtil.isEmpty(proxyPassword) || EasyUtil.isEmpty(proxyUser) && EasyUtil.isEmpty(proxyPassword)) {
                    if (EasyUtil.checkIp(address) && EasyUtil.checkPort(port)) {
                        Ipool ipool = ipoolService.findByUserIdAndId(userId, Long.parseLong(id));
                        if (type == 0 && ipool != null) {
                            ipool.setProxyPassword(proxyPassword);
                            ipool.setProxyUser(proxyUser);
                            ipool.setAddress(address);
                            ipool.setPort(port);
                            ipool.setType(type);
                            ipool.setCountry(country);
                            ipoolService.saveIpool(ipool);
                            message.setSuccess(true);
                            message.setMessage("IP信息修改成功!");
                        } else {
                            message.setSuccess(false);
                            message.setMessage("IP类型不合法!");
                        }
                    } else {
                        message.setSuccess(false);
                        message.setMessage("IP信息不合法!");
                    }
                } else {
                    message.setSuccess(false);
                    message.setMessage("代理信息必须有账号密码信息或者都不填!");
                }
            } else {
                message.setSuccess(false);
                message.setMessage("IP信息不能为空!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("用户异常!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/addIp", method = RequestMethod.POST)
    @ResponseBody
    public String addIp(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId)) {
            userId = desHelper.decrypt(userId);
            String addIpForm = JSONObject.toJSONString(jsonObject.get("addIpForm"));
            JSONObject temp = JSONObject.parseObject(addIpForm);
            if (!EasyUtil.isEmpty(userId) && temp != null && temp.size() > 0) {
                String address = temp.getString("address");
                String port = temp.getString("port");
                String proxyUser = temp.getString("proxyUser");
                String proxyPassword = temp.getString("proxyPassword");
                Integer type = 0;//只用luminati old==>temp.getInteger("type");
                if (!EasyUtil.isEmpty(address) && !EasyUtil.isEmpty(port)) {
                    if (!EasyUtil.isEmpty(proxyUser) && !EasyUtil.isEmpty(proxyPassword) || EasyUtil.isEmpty(proxyUser) && EasyUtil.isEmpty(proxyPassword)) {
                        boolean isIp = EasyUtil.checkIp(address);
                        boolean isPort = EasyUtil.checkPort(port);
                        if (isIp && isPort && !EasyUtil.isEmpty(country)) {
                            Ipool tempIp = ipoolService.findByAddressAndPortAndUserIdAndCountry(address, port, userId, country);
                            if (tempIp == null) {
                                Ipool ipool = new Ipool();
                                ipool.setUsestatus(0);
                                ipool.setAddress(address.trim());
                                ipool.setPort(port.trim());
                                if (!EasyUtil.isEmpty(proxyUser)) {
                                    ipool.setProxyUser(proxyUser.trim());
                                }
                                if (!EasyUtil.isEmpty(proxyPassword)) {
                                    ipool.setProxyPassword(proxyPassword.trim());
                                }
                                ipool.setUserId(userId);
                                ipool.setType(type);
                                ipool.setCountry(country);
                                ipool.setBind(0);
                                ipoolService.saveIpool(ipool);
                                message.setSuccess(true);
                                message.setMessage("IP添加成功!");
                            } else {
                                message.setSuccess(false);
                                message.setMessage("ip信息已存在!");
                            }
                        } else {
                            message.setSuccess(false);
                            message.setMessage("ip信息不合法!");
                        }
                    } else {
                        message.setSuccess(false);
                        message.setMessage("代理信息必须有账号密码信息或者都不填!");
                    }
                } else {
                    message.setSuccess(false);
                    message.setMessage("IP或端口不能为空!");
                }
            } else {
                message.setSuccess(false);
                message.setMessage("参数异常!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("用户异常!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/delIP", method = RequestMethod.POST)
    @ResponseBody
    public String delIP(@RequestBody JSONObject jsonObject) {
        Message message = new Message();
        String userId = jsonObject.getString("userId");
        JSONArray list = jsonObject.getJSONArray("ipSelectList");
        List<Ipool> ipools = list.toJavaList(Ipool.class);
        if (!EasyUtil.isEmpty(userId)) {
            String tempUserId = desHelper.decrypt(userId);
            if (ipools != null && ipools.size() > 0) {
                ipools.stream().forEach(f -> {
                    if (f.getUsestatus() == 0) {
                        ipoolService.deleteByIdAndUserId(f.getId(), tempUserId);
                    }
                });
                message.setMessage("删除成功!");
                message.setSuccess(true);
            } else {
                message.setMessage("删除的数据不存在!");
                message.setSuccess(false);
            }
        } else {
            message.setMessage("用户异常!");
            message.setSuccess(false);
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/getIpList", method = RequestMethod.POST)
    @ResponseBody
    public Page<Ipool> getIpList(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        Integer type = jsonObject.getInteger("type");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageNumber = jsonObject.getInteger("pageNumber");
        if (!EasyUtil.isEmpty(userId) && type != null) {
            userId = desHelper.decrypt(userId);
            Page<Ipool> list = ipoolService.findByUserIdAndTypeAndCountryPage(userId, type, pageSize, pageNumber, country);
            return list;
        }
        return null;
    }

    @RequestMapping(value = "/inputIPFile", method = RequestMethod.POST)
    @ResponseBody
    public String inputIPFile(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId, @RequestParam("country") String country, @RequestParam("type") Integer type) {
        Message message = new Message();
        if (!file.isEmpty()) {
            if (!EasyUtil.isEmpty(userId)) {
                userId = desHelper.decrypt(userId);
                List<Ipool> ipoolList = EasyUtil.readIPExcel(file, type, userId, country);
                if (ipoolList != null & ipoolList.size() > 0) {
                    if (type == 0) {
                        List<Ipool> collect = ipoolList.stream().filter(f -> !EasyUtil.isEmpty(f.getProxyUser()) && !EasyUtil.isEmpty(f.getProxyPassword()) ||
                                EasyUtil.isEmpty(f.getProxyUser()) || EasyUtil.isEmpty(f.getProxyPassword())).collect(Collectors.toList());
                        ipoolService.saveAll(collect);
                        message.setMessage("上传成功!");
                        message.setSuccess(true);
                    } else {
                        message.setMessage("IP类型异常!");
                        message.setSuccess(false);
                    }
                } else {
                    message.setMessage("文件中没有数据!");
                    message.setSuccess(false);
                }
            } else {
                message.setMessage("用户异常!");
                message.setSuccess(false);
            }
        } else {
            message.setMessage("上传失败，因为文件是空的!");
            message.setSuccess(false);
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/resetIP", method = RequestMethod.POST)
    @ResponseBody
    public String resetIP(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(country)) {
            userId = desHelper.decrypt(userId);
            List<Ipool> list = ipoolService.findByUserIdAndUsestatusAndCountry(userId, 1, country);
            list.stream().forEach(f -> {
                ipoolService.updateUsestatus(f.getId(), 0);
            });
            message.setMessage("重置成功!");
            message.setSuccess(true);
        } else {
            message.setMessage("用户异常!");
            message.setSuccess(false);
        }
        return JSONObject.toJSONString(message);
    }


}
